package string.compare;

/**
 * @Classname : PalindromicSubstrings
 * @Description : 647. 回文子串
 * https://leetcode.cn/problems/palindromic-substrings/
 * @Author : chentianyu
 * @Date 2022/12/9 00:03
 */


public class PalindromicSubstrings {
    public int countSubstrings(String s) {
        int count = 0;
        // 遍历统计每个位置上的回文子串个数
        for (int i = 0; i < s.length(); i++) {
            count += countNumOfCurrentPosition(i, i, s);  // 奇数回文子串
            count += countNumOfCurrentPosition(i - 1, i, s);  // 偶数回文子串
        }
        return count;
    }

    private int countNumOfCurrentPosition(int l, int r, String s) {
        int count = 0;
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            count++;
            l--;
            r++;
        }
        return count;
    }
}
